import tkinter as tk
from tkinter import filedialog
import re
import os
import glob

def replace_sleep_times(code_path, new_times):
    # 单位分钟转换为毫秒
    new_times = new_times * 60 * 1000
    # 读取文件内容
    with open(code_path, 'r' ,encoding='gbk', errors='ignore') as file:
        code = file.read()

    # 正则表达式用于匹配 threadSleep() 中的数字
    pattern = r'testWaitForTimeout\((\d+)\);'
    pattern1 = r'threadSleep\((\d+)\);'
    # 使用 findall() 查找所有匹配的时间
    times = re.findall(pattern, code)
    if not times:
        return code  # 如果没有匹配项，返回原代码

    str_new = "testWaitForTimeout(" + str(int(new_times / len(times))) + ");"
    pattern = r'testWaitForTimeout\(\d+\);'
    # 使用 sub() 函数替换所有匹配的时间
    new_code = re.sub(pattern, str_new, code)

    # 构建新的文件路径
    base, ext = os.path.splitext(code_path)
    new_file_path = base + "_optimize" + ext

    # 写入新文件
    with open(new_file_path, 'w') as file:
        file.write(new_code)

    return new_file_path

def load_file():
    filepath = filedialog.askopenfilename(initialdir=".", title="Select file",
                                          filetypes=(("can files", "*.can"), ("all files", "*.*")))
    if filepath:
        path_entry.delete(0, tk.END)
        path_entry.insert(0, filepath)

def update_code():
    file_path = path_entry.get()
    new_time = int(time_entry.get())
    new_file_path = replace_sleep_times(file_path, new_time)
    result_label.config(text="更新并保存成功！新文件: " + os.path.basename(new_file_path))

# 查找当前路径下的第一个.can文件
default_can_file = glob.glob('*.can')[0] if glob.glob('*.can') else ""

# 创建窗口
root = tk.Tk()
root.title("Update and Save Sleep Times in CAN File")

# 布局
tk.Label(root, text="文件路径:").grid(row=0, column=0)
path_entry = tk.Entry(root, width=50)
path_entry.grid(row=0, column=1)
path_entry.insert(0, default_can_file)
tk.Button(root, text="浏览", command=load_file).grid(row=0, column=2)

tk.Label(root, text="新时间（分钟）:").grid(row=1, column=0)
time_entry = tk.Entry(root, width=20)
time_entry.grid(row=1, column=1)
time_entry.insert(0, "20")

tk.Button(root, text="更新并保存", command=update_code).grid(row=2, column=1)

result_label = tk.Label(root, text="")
result_label.grid(row=3, column=1)

# 运行主循环
root.mainloop()
